<template>
  <a-modal v-model:visible="visible" title="客户分配" @ok="handleOk" @cancel="handleCancel" :destroyOnClose="true" :bodyStyle="{ padding: '24px' }" class="custom-modal" :okButtonProps="{ disabled: confirmLoading }">
    <a-form layout="horizontal" :labelCol="{ span: 3 }" :wrapperCol="{ span: 24 }">
      <a-form-item label="分配人：" required>
        <a-select v-model:value="selectedUserId" placeholder="请选择分配人" style="width: 100%" :disabled="confirmLoading">
          <a-select-option v-for="user in userList" :key="user.id" :value="user.id">
            {{ user.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<style scoped>
.custom-modal .ant-modal-body {
  padding: 24px !important;
}
</style>
<script setup lang="ts">
import { ref, defineExpose } from 'vue';
import { message } from 'ant-design-vue';

const visible = ref(false);
const userList = ref<{ id: string; name: string }[]>([]);
const selectedUserId = ref<string | null>(null);
const currentRecord = ref<any>(null); // 保存当前记录
const confirmLoading = ref<boolean>(false); // 添加确认按钮加载状态

const emit = defineEmits(['ok', 'cancel']);

function open(users: { id: string; name: string }[], record?: any) {
  userList.value = users;
  currentRecord.value = record;
  selectedUserId.value = null;
  confirmLoading.value = false; // 重置按钮状态
  
  // 如果传入了记录且记录中有负责人，则设置默认选中
  if (record && record.responsibleName) {
    const responsibleUser = users.find(user => user.name === record.responsibleName);
    if (responsibleUser) {
      selectedUserId.value = responsibleUser.id;
    }
  }
  
  visible.value = true;
}

function handleOk() {
  const user = userList.value.find(u => u.id === selectedUserId.value);
  if (user) {
    confirmLoading.value = true; // 设置按钮为加载状态，禁用按钮
    emit('ok', user);
    // 不在这里关闭模态框，让父组件在任务分配成功后再关闭
  } else {
    // 如果没有选择用户，提示用户选择
    message.warning('请选择分配人');
  }
}

function handleCancel() {
  if (confirmLoading.value) {
    return; // 如果正在提交，则不允许取消
  }
  emit('cancel');
  visible.value = false;
}

// 添加重置方法，用于在任务分配失败时重置按钮状态
function resetConfirmLoading() {
  confirmLoading.value = false;
}

defineExpose({ open, visible, currentRecord, resetConfirmLoading });
</script>